import { ref, computed, onMounted, onBeforeUnmount, nextTick, watch } from "vue";

// 增强版虚拟列表composable，支持动态高度和更好的性能
export function useVirtualList(options = {}) {
  const {
    itemHeight = 72,
    overscan = 6,
    containerRef = null,
    total = 0,
    enableDynamicHeight = false,
    estimatedItemHeight = 72,
    threshold = 100, // 滚动阈值，用于节流
  } = options;

  const scrollTop = ref(0);
  const containerHeight = ref(0);
  const itemHeights = ref(new Map()); // 存储每个item的实际高度
  const itemPositions = ref(new Map()); // 存储每个item的位置
  const totalHeight = ref(0);
  const isScrolling = ref(false);
  const scrollDirection = ref('down');
  const lastScrollTop = ref(0);

  // 计算总高度
  const calculateTotalHeight = () => {
    if (enableDynamicHeight) {
      let height = 0;
      for (let i = 0; i < total; i++) {
        const itemHeight = itemHeights.value.get(i) || estimatedItemHeight;
        itemPositions.value.set(i, height);
        height += itemHeight;
      }
      totalHeight.value = height;
    } else {
      totalHeight.value = total * itemHeight;
    }
  };

  // 获取item位置
  const getItemPosition = (index) => {
    if (enableDynamicHeight) {
      return itemPositions.value.get(index) || 0;
    }
    return index * itemHeight;
  };

  // 获取item高度
  const getItemHeight = (index) => {
    if (enableDynamicHeight) {
      return itemHeights.value.get(index) || estimatedItemHeight;
    }
    return itemHeight;
  };

  // 二分查找开始索引
  const findStartIndex = (scrollTop) => {
    if (!enableDynamicHeight) {
      return Math.max(Math.floor(scrollTop / itemHeight) - overscan, 0);
    }

    let left = 0;
    let right = total - 1;
    let startIndex = 0;

    while (left <= right) {
      const mid = Math.floor((left + right) / 2);
      const position = getItemPosition(mid);
      
      if (position <= scrollTop) {
        startIndex = mid;
        left = mid + 1;
      } else {
        right = mid - 1;
      }
    }

    return Math.max(startIndex - overscan, 0);
  };

  // 计算可见范围
  const calculateVisibleRange = () => {
    const start = findStartIndex(scrollTop.value);
    let end = start;
    let currentHeight = 0;
    const viewportHeight = containerHeight.value;

    for (let i = start; i < total; i++) {
      const itemHeight = getItemHeight(i);
      if (currentHeight + itemHeight > viewportHeight + overscan * itemHeight) {
        break;
      }
      currentHeight += itemHeight;
      end = i;
    }

    return {
      startIndex: start,
      endIndex: Math.min(end + 1, total)
    };
  };

  const visibleRange = computed(() => calculateVisibleRange());
  const startIndex = computed(() => visibleRange.value.startIndex);
  const endIndex = computed(() => visibleRange.value.endIndex);
  const visibleCount = computed(() => endIndex.value - startIndex.value);

  const offsetTop = computed(() => {
    if (enableDynamicHeight) {
      return getItemPosition(startIndex.value);
    }
    return startIndex.value * itemHeight;
  });

  // 节流滚动处理
  let scrollTimer = null;
  function onScroll(e) {
    const currentScrollTop = e.target.scrollTop;
    scrollDirection.value = currentScrollTop > lastScrollTop.value ? 'down' : 'up';
    lastScrollTop.value = currentScrollTop;
    scrollTop.value = currentScrollTop;
    isScrolling.value = true;

    // 清除之前的定时器
    if (scrollTimer) {
      clearTimeout(scrollTimer);
    }

    // 设置新的定时器
    scrollTimer = setTimeout(() => {
      isScrolling.value = false;
    }, 150);
  }

  // 测量容器高度
  function measure() {
    if (!containerRef || !containerRef.value) return;
    containerHeight.value = containerRef.value.clientHeight;
  }

  // 更新item高度
  function updateItemHeight(index, height) {
    if (enableDynamicHeight && height > 0) {
      const oldHeight = itemHeights.value.get(index) || estimatedItemHeight;
      if (Math.abs(oldHeight - height) > 1) { // 只有高度变化超过1px才更新
        itemHeights.value.set(index, height);
        calculateTotalHeight();
      }
    }
  }

  // 滚动到指定位置
  function scrollTo(index, behavior = 'smooth') {
    if (!containerRef || !containerRef.value) return;
    
    const position = getItemPosition(index);
    containerRef.value.scrollTo({
      top: position,
      behavior
    });
  }

  // 滚动到底部
  function scrollToBottom(behavior = 'smooth') {
    if (!containerRef || !containerRef.value) return;
    
    containerRef.value.scrollTo({
      top: totalHeight.value,
      behavior
    });
  }

  // 滚动到顶部
  function scrollToTop(behavior = 'smooth') {
    if (!containerRef || !containerRef.value) return;
    
    containerRef.value.scrollTo({
      top: 0,
      behavior
    });
  }

  // 获取可见的items
  const visibleItems = computed(() => {
    const items = [];
    for (let i = startIndex.value; i < endIndex.value; i++) {
      items.push({
        index: i,
        position: getItemPosition(i),
        height: getItemHeight(i)
      });
    }
    return items;
  });

  // 监听total变化，重新计算高度
  watch(() => total, () => {
    calculateTotalHeight();
  }, { immediate: true });

  onMounted(() => {
    if (containerRef && containerRef.value) {
      containerRef.value.addEventListener("scroll", onScroll, { passive: true });
    }
    window.addEventListener("resize", measure, { passive: true });
    measure();
    calculateTotalHeight();
  });

  onBeforeUnmount(() => {
    if (containerRef && containerRef.value) {
      containerRef.value.removeEventListener("scroll", onScroll);
    }
    window.removeEventListener("resize", measure);
    if (scrollTimer) {
      clearTimeout(scrollTimer);
    }
  });

  return {
    // 基础属性
    startIndex,
    endIndex,
    offsetTop,
    visibleCount,
    totalHeight,
    isScrolling,
    scrollDirection,
    visibleItems,
    
    // 方法
    onScroll,
    measure,
    updateItemHeight,
    scrollTo,
    scrollToBottom,
    scrollToTop,
    getItemPosition,
    getItemHeight,
  };
}


